import 'dart:async';
import 'dart:collection';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/const/AppConst.dart';
import 'package:wk_robot2/app/storage/StorageManager.dart';
import 'package:wk_robot2/app/utils/PermissionUtil.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';

import '../../../const/AppConstUrl.dart';
import '../../../event/DataCallBack.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/NetWorkUtil.dart';
import '../../../widget/tips.dart';
import '../../componentview/controllers/IndexViewController.dart';
import '../views/login_view.dart';

class LoginController extends GetxController with WidgetsBindingObserver {

  var passwordVisible = false.obs;
  var checkBoxChecked = false.obs;

  var countDown = 60.obs;
  var buttonText = '获取验证码'.obs;
  var buttonIsAble = true.obs;

  Timer? _timer;


  var accountController = TextEditingController().obs;
  var validateCodeController = TextEditingController().obs;

  var isSubmitBtnEnable = false.obs;

  static const platform = MethodChannel('com.youbixuan.wk2/channel');

  var scrollController = ScrollController().obs;

  late StreamSubscription<bool> keyboardSubscription;

  var suffixIconsVisible = false.obs;

  var phoneTextFieldEditable = true.obs;

  FocusNode validateFocusNode = FocusNode();
  FocusNode phoneFocusNode = FocusNode();


  @override
  void onInit() {
    super.onInit();
    var keyboardVisibilityController = KeyboardVisibilityController();
    // Query
    print('Keyboard visibility direct query: ${keyboardVisibilityController.isVisible}');

    // Subscribe
    keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');
      if(visible) {
        //scrollToBottom();
        Future.delayed(Duration(milliseconds: 200), () {
           scrollToBottom();
        });

      }
    });


    // 监听焦点变化
    phoneFocusNode.addListener(() {
      if (phoneFocusNode.hasFocus) {
        suffixIconsVisible.value = true;

      } else {
        suffixIconsVisible.value = false;
      }
    });

  }


  @override
  void onReady() {
    super.onReady();

    if(!StorageManager.getStorage().hasData(AppConst.storage_key_user_protocol_has_read) ||
        StorageManager.getStorage().read(AppConst.storage_key_user_protocol_has_read) == false) {
        CommonWidgets.showConfirmDialogForUserProtocol(Get.context!,DataCallBack(
            confirmCallBack: (v) {
               StorageManager.getStorage().write(AppConst.storage_key_user_protocol_has_read, true);


            },
            cancleCallBack: (v)  {
              StorageManager.getStorage().write(AppConst.storage_key_user_protocol_has_read, false);
              platform.invokeMethod('exitApp');
            }

      ),onTapUserAgreementTask,onTapPrivacyPolicyTask);
    }
  }

  void onTapUserAgreementTask(){
    Map<String, String> param = HashMap();
    param["title"] = "用户协议";
    param["url"] = AppConstUrl.LOGIN_USER_AGREEMENT_URL;
    Get.toNamed(Routes.WEBVIEW, parameters: param);
  }

  void onTapPrivacyPolicyTask(){
    Map<String, String> param = HashMap();
    param["title"] = "隐私政策";
    param["url"] = AppConstUrl.LOGIN_PRIVACY_POLICY_URL;
    Get.toNamed(Routes.WEBVIEW, parameters: param);
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.value.dispose();
    keyboardSubscription.cancel();

    if (_timer != null) {
      _timer!.cancel();
    }
  }



  void changePasswordVisible(bool isView) {
    passwordVisible.value = !isView;
  }


  void startRequestValidateCode () async {
    if (!buttonIsAble.value) {
      return;
    }
    //做权限检查.
    bool isNetWork = await NetWorkUtil.checkNetWorkIsAvailable();
    if (!isNetWork) {
      Tips.showToast('网络不可用.');
      return;
    }


    // 验证邮箱的合法性.
    if(accountController.value.text.isEmpty) {
      Tips.showToast('手机号不能为空.');
      return;
    }


    // 请求接口,发送邮箱验证码.
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.GET_MSG_VALIDATE_CODE, {
         'account': accountController.value.text,
         'accountType': '0',
         'purpose': '3'

    }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (data) {
          Tips.showToast('验证码已发送.');
          buttonIsAble.value = false;
          buttonText.value = countDown.value.toString() +"秒";

          phoneTextFieldEditable.value = false;

          _timer = Timer.periodic(Duration(seconds: 1), (timer) {
            if (countDown.value < 1) {
              timer.cancel();
              buttonIsAble.value = true;
              buttonText.value = '获取验证码';
              countDown.value = 60;
              phoneTextFieldEditable.value = true;
            } else {
              countDown.value = countDown.value - 1;
              buttonText.value = countDown.value.toString() +"秒";
            }
          });


        }
    ),showLoading: true);

  }

  void scrollToBottom() {
    double top = scrollController.value.position.maxScrollExtent;
    scrollController.value.jumpTo(
      top,
    );
    /*scrollController.value.animateTo(
      scrollController.value.position.maxScrollExtent,
      duration: const Duration(seconds: 1),
      curve: Curves.easeOut,
    );*/
  }


  void setSuffixIconsVisible(bool visible) {
    suffixIconsVisible.value = visible;
  }

  void onTextFieldChange(v) {
      if (v != null && v != '') {
        suffixIconsVisible.value = true;
      } else {
        suffixIconsVisible.value = false;
      }

      //检查btn提交按钮是否可以点击.
      if(simpleChecking()) {
        isSubmitBtnEnable.value = true;
      } else {
        isSubmitBtnEnable.value = false;
      }
  }

  void onValidateCodeChange(v) {
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }

  }

  void onCheckBoxChange() {
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }
  }


  bool simpleChecking() {
    return accountController.value.text != '' && validateCodeController.value.text != '';
  }

  void requestLogin () {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.USER_LOGINING, {
      "account": accountController.value.text,
      "captcha": validateCodeController.value.text,
      "countryCode": "+86"
    }, NetWorkManager.methodPOST, DataCallBack(
        businessCallBack: (data) {
          StorageManager.getStorage().write(AppConst.storage_key_login_token, data['token']);
          StorageManager.getStorage().write(AppConst.storage_current_login_user, data['user']);
          eventBus.fire(ProductContentEvent(ACCOUNT_INFO_REFRESH));

          if (GetInstance().isRegistered<IndexViewController>()) {
            IndexViewController indexInstance =  GetInstance().find<IndexViewController>();
            if (indexInstance != null) {
              indexInstance.retrieveRobots();
            }
          }

          Get.offNamed(Routes.HOME);
        },
        errorCallBack: (error) {
          Tips.showToast(error);
        }
    ),showLoading: true);
  }

}
